<?php


namespace frontend\themes\basic\_widgets;

use Yii;
use yii\db\Query;
use yii\bootstrap\Nav;
use yii\bootstrap\Widget;
use yii\helpers\StringHelper;
use common\components\Tree;

class MenuWidget extends Widget
{
    public $type;
    public $table = '{{%menu}}';
    private $_menus;

    public function init()
    {
        parent::init();
        $this->_menus = (new Query())->from($this->table)
            ->where([
                'menutype' => $this->type,
                'language' => ['*', Yii::$app->language]
            ])
            ->orderBy('lft')
            ->all();
    }

    public function run()
    {
        $tree = new Tree($this->_menus, ['parent_key' => 'parent']);
        $treeMenus = $tree->makeTree(0, 2);
        $menuItems = [];
        foreach ($treeMenus as $menu) {
            $menuItems[] = $this->_menuItem($menu);
        }

        return Nav::widget([
            'options' => ['class' => 'navbar-nav navbar-left'],
            'items' => $menuItems
        ]);
    }

    private function _menuItem($menu)
    {
        $menuItem = [];
        if ($menu['type'] === 'module'){
            if (StringHelper::startsWith($menu['route'], '@' . Yii::$app->id)) {
                $route = [strstr($menu['route'], '/')];
                $request = json_decode($menu['request'], true) ?? [];
                $url = array_merge($route, $request);
                $menuItem = ['label' => $menu['name'], 'url' => $url];
            }
        }elseif ($menu['type'] === 'url'){
            $menuItem =  ['label' => $menu['name'], 'url' => ['/'.$menu['route']]];
        }elseif ($menu['type'] === 'alias'){
            $params = json_decode($menu['params'],true);
            $menuData = (new Query())->from($this->table)->where(['id' => $params['menu_id']])->one();
            if ($menuData){
                if ($params['alias_redirect']){
                    $menuData['name'] = $menu['name'];
                    return $this->_menuItem($menuData);
                }
            }
            $menuItem =  ['label' => $menu['name'], 'url' => ['/'.$menu['path']]];
        }

        if ($menu['browserNav']){
            $menuItem['linkOptions'] = ['target' => '_blank'];
        }

        if (isset($menu['children']) && !empty($menu['children'])){
            foreach ($menu['children'] as $child) {
                $menuItem['items'][] = $this->_menuItem($child);
            }
        }

        return $menuItem;
    }
}